//
//  VL5CallVideoVController.m
//  DoorBell
//
//  Created by eques on 2024/4/2.
//  Copyright © 2024 eques. All rights reserved.
//

#import "VL5CallVideoVController.h"
#import "FBDevicesList.h"
#import "AppDelegate.h"
#import "SecurityPwdView.h"
#import <Photos/Photos.h>
#define VL5Closetime          120 // VL5 4g挂断时间
#define NewButtonSize         50
@interface VL5CallVideoVController ()<SecurityPwdViewDelegate>
//视频展示容器
@property(nonatomic,strong)UIView *call_view;
@property(nonatomic,strong)UILabel *vl0TimeLabel;
//设备信息
@property(nonatomic,strong)FBDevicesList *devices;

/*定时器*/
@property (nonatomic,strong) dispatch_source_t open_vl0_time;
@property (nonatomic,strong) dispatch_source_t can_open_vl0_time;
@property (nonatomic,strong) dispatch_source_t wake_up_timer;
@property (nonatomic,strong) dispatch_source_t change_camera_post;

@property (nonatomic,weak) NSTimer *timer;//视频播放时间计时器
@property (nonatomic,weak) NSTimer *wait_timer;//呼叫等待计时器
@property (nonatomic,weak) NSTimer *waittingVideoTimer;//视频加载动画定时器

//开锁按钮倒计时图片
@property (nonatomic,strong)UIImageView *lockImageview;

//等待动画
@property (nonatomic,strong)UIImageView *annimationImage;
//视频加载中
@property(nonatomic,strong)UILabel *loadingLabel;

//宽高比
@property (nonatomic,assign)float w_h;

/*Micro状态*/
@property (nonatomic, assign) bool bopenMicro;
/*是否取消唤醒*/
@property (nonatomic, assign) bool cancelpost;
/*是否发送呼叫邀请*/
@property (nonatomic, assign) bool isSendInvite;

/*成功展示视频界面*/
@property (nonatomic, assign) bool sucess_call;
@property (nonatomic,strong) NSDate *date;

/*Micro状态*/
@property (nonatomic, assign) int soundType;
/*切换摄像头index*/
@property (nonatomic, assign) int camera_index;

//对讲按钮
@property (nonatomic,strong) UIButton *speakButton;
//静音按钮
@property (nonatomic,strong) UIButton *mirButton;
//挂断按钮
@property (nonatomic,strong) UIButton *hanupButton;
@property (nonatomic,strong) SecurityPwdView *lowView;


//视频呼叫等待界面时的挂断按钮
@property (nonatomic,strong) UIButton *hanup_Button;
@property (nonatomic,assign) int camera_id;
@end

@implementation VL5CallVideoVController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor blackColor];
    
    //开锁指令设备收到回复
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(open_smart_lock_result:) name:OPEN_SMART_LOCK_RESULT object:nil];
    
    //开锁指令设备反馈结果
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(open_smart_lock_response:) name:OPEN_SMART_LOCK_RESPONSE object:nil];
    
    //设备上下线通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devst:) name:DEVST object:nil];
    
    //创建视频通道失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(errorVideo:) name:equesOnMessageVideocCreateChannelFail object:nil];
    
    //连接对端设备失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(errorVideo:) name:equesOnMessageVideocConnectPeerFail object:nil];
    

    //对端设备断开
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RecvCallTimeoutMsg:) name:equesOnMessageVideocTimeOut object:nil];
    
    //超时或其他异常需要挂断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(byebyeCall) name:equesOnMessageVideocCallClose object:nil];
    
    //开始播放
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RecvPlayingMessage:) name:equesOnMessageVideoplayingNotification object:nil];
    
    //切换摄像头回复
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(switch_camera_response:) name:SWITCH_CAMERA_RESPONSE object:nil];

    self.devices = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    if(self.devices.videocall_width > self.devices.videocall_height){
        self.w_h = (CGFloat)self.devices.videocall_width/self.devices.videocall_height;
    }else{
        self.w_h = (CGFloat)self.devices.videocall_height/self.devices.videocall_width;
    }
    
    self.w_h = self.w_h > 0 ? self.w_h : 1.8;
    
    [self addCallview];
    
    [self addVoiceImage];
    
     self.hanup_Button.backgroundColor = [UIColor clearColor];
     self.loadingLabel.text = @"视频加载中...";
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self wake_up_device];
    
    [self loadingForVideoAnimation];
}

- (void)wake_up_device
{
    __weak VL5CallVideoVController *weakSelf = self;
    
    self.devices = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    // 在线
    if (self.devices.status == 1){
        
        NSDate* dat = [NSDate date];
        NSTimeInterval hangupTime= [dat timeIntervalSince1970];
        NSLog(@"current Time-->%f",hangupTime);
        
        AppDelegate *de = (AppDelegate*) [[UIApplication sharedApplication] delegate];
        NSLog(@"de.hangupTime-->%f",de.hangupTime);
        float time = hangupTime - de.hangupTime;
        
        NSLog(@"呼叫时间间隔 hangupTime - de.hangupTime -->%f deviceNewInfo.status-->%d",time,self.devices.status);
        //记录上次呼叫的挂断时间 防止频繁呼叫导致问题
        if (time <= 6) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
                self.devices = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                // 等设备睡眠 再发起呼叫
                if (self.devices.status == 2 || self.devices.status == 0) {
                    
                           // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                            __block int timeout = 30*5*200; // 倒计时时间
                            self.cancelpost = NO;
                             dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                            weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                            dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每200毫秒执行
                            dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                                if(self.cancelpost){ // 倒计时结束，关闭
                                    dispatch_source_cancel(weakSelf.wake_up_timer);
                                    weakSelf.wake_up_timer = nil;
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            if (!self.isSendInvite) {
                                                [self makeCall];
                                                 self.isSendInvite = YES;
                                            }
                                        });
                                    });
                    
                                }else{
                                    NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                                    [YKBusinessFramework equesSendData:Str];
                                    NSLog(@"wake_up_t1_r700 == %@",Str);
                                     timeout-=200;
                                    if (timeout <= 0) {
                                        dispatch_source_cancel(weakSelf.wake_up_timer);
                                        weakSelf.wake_up_timer = nil;
                                    }
                                }
                            });
                    dispatch_resume(weakSelf.wake_up_timer);
                    
                //还在线
                }else{
                    
                    if (!self.isSendInvite) {
                        [self makeCall];
                         self.isSendInvite = YES;
                    }
                }
            });
            
        }else{
        
            if (!self.isSendInvite) {
                [self makeCall];
                 self.isSendInvite = YES;
            }
      }

    // 睡眠下 去唤醒
    }else if(self.devices.status == 2){
        
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        __block int timeout = 30*5*200; // 倒计时时间
        self.cancelpost = NO;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每200毫秒秒执行
        dispatch_source_set_event_handler(_wake_up_timer, ^{
            if(self.cancelpost){ // 倒计时结束，关闭
                dispatch_source_cancel(weakSelf.wake_up_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        if (!self.isSendInvite) {
                            [self makeCall];
                             self.isSendInvite = YES;
                        }
                    });
                });
            }else{
                 NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                [YKBusinessFramework equesSendData:Str];
                NSLog(@"wake_up_t1_r700 == %@",Str);
                 timeout-=200;
                if (timeout <= 0) {
                    dispatch_source_cancel(weakSelf.wake_up_timer);
                    weakSelf.wake_up_timer = nil;
                }
            }
        });
         dispatch_resume(weakSelf.wake_up_timer);
  
    //设备掉线
    }else if(self.devices.status == 0){
        
    
        // 呼叫时设备已经掉线
        if (self.devices.status == 0) {
            
            //延迟2秒 防止掉线后上线
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                self.devices = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                
                //设备确实掉线了 直接挂断 不统计呼叫结果
                if (self.devices.status == 0) {
                   [self byebyeCall];
                    
                // 三秒后上线 直接呼叫
                }else if (self.devices.status == 1){
                    
                    if (!self.isSendInvite) {
                       [self makeCall];
                        self.isSendInvite = YES;
                    }
                    
                }else{
                    
                    // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                    __block int timeout = 30*5*200; // 倒计时时间
                    self.cancelpost = NO;
                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                    dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每200毫秒执行
                    dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                        if(self.cancelpost){ // 倒计时结束，关闭
                            dispatch_source_cancel(weakSelf.wake_up_timer);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    if (!self.isSendInvite) {
                                        [self makeCall];
                                         self.isSendInvite = YES;
                                    }
                                });
                            });
                        }else{
                            NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                            [YKBusinessFramework equesSendData:Str];
                            NSLog(@"wake_up_t1_r700 == %@",Str);
                             timeout-=200;
                            if (timeout <= 0) {
                                dispatch_source_cancel(weakSelf.wake_up_timer);
                                weakSelf.wake_up_timer = nil;
                            }
                        }
                    });
                     dispatch_resume(weakSelf.wake_up_timer);
                }
            });
            
        }else{
           
            // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
            __block int timeout = 30*5*200; // 倒计时时间
            self.cancelpost = NO;
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            _wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
            dispatch_source_set_event_handler(_wake_up_timer, ^{
                if(self.cancelpost){ // 倒计时结束，关闭
                    dispatch_source_cancel(weakSelf.wake_up_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            if (!self.isSendInvite) {
                                [self makeCall];
                                 self.isSendInvite = YES;
                            }
                        });
                    });
                }else{
                    NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                    [YKBusinessFramework equesSendData:Str];
                     NSLog(@"wake_up_t1_r700 == %@",Str);
                     timeout-=200;
                    if (timeout <= 0) {
                        dispatch_source_cancel(weakSelf.wake_up_timer);
                        weakSelf.wake_up_timer = nil;
                    }
                }
            });
             dispatch_resume(_wake_up_timer);
          }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:equesOnMessageVideoplayingNotification object:nil];//视频连接成功后出现画面
    [[NSNotificationCenter defaultCenter] removeObserver:self name:equesOnMessageVideocCreateChannelFail object:nil];//创建视频通道失败
    [[NSNotificationCenter defaultCenter] removeObserver:self name:equesOnMessageVideocConnectPeerFail object:nil];//连接对端设备失败
    [[NSNotificationCenter defaultCenter] removeObserver:self name:OPEN_SMART_LOCK_RESPONSE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:OPEN_SMART_LOCK_RESULT object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:DEVST object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"timeout" object:nil];//视频拨打超时
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Call_Close" object:nil];//设备端主动退出视频
}





#pragma mark 视频播放状态
- (void)RecvPlayingMessage:(NSNotification *)notification
{
   
    __weak VL5CallVideoVController *weakSelf = self;

    
    NSLog(@"视频播放 RecvPlayingMessage～ \n");
    self.date = [NSDate date];
    
    self.sucess_call = YES;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if(weakSelf.waittingVideoTimer){
            [weakSelf.waittingVideoTimer invalidate];
            weakSelf.waittingVideoTimer = nil;
        }
        [self.annimationImage stopAnimating];
         self.annimationImage.hidden = YES;
         self.hanup_Button.hidden = YES;
         self.loadingLabel.hidden = YES;
        
        weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(showTime) userInfo:nil repeats:YES];
       [[NSRunLoop mainRunLoop] addTimer:weakSelf.timer forMode:NSDefaultRunLoopMode];
   
        self.speakButton.backgroundColor = [HexChangeRGB colorWithHexString:@"#fbf8f3"];
        self.hanupButton.backgroundColor = [UIColor clearColor];
       
       NSString *strMicrophone = [[NSUserDefaults standardUserDefaults] objectForKey:@"isopenmicro"];
       if(strMicrophone == nil){
           
           [self.mirButton setImage:[UIImage imageNamed:@"mute_off_vl2.png"] forState:UIControlStateNormal];
           weakSelf.bopenMicro = true;
       }else if ([strMicrophone isEqualToString:@"0"]) {
           
           [self.mirButton setImage:[UIImage imageNamed:@"mute_on_vl2.png"] forState:UIControlStateNormal];
           weakSelf.bopenMicro = false;
       }else{
           [self.mirButton setImage:[UIImage imageNamed:@"mute_off_vl2.png"] forState:UIControlStateNormal];
           weakSelf.bopenMicro = true;
       }
        [self.view bringSubviewToFront:self.speakButton];
        [self.view bringSubviewToFront:self.hanupButton];
        [self.view bringSubviewToFront:self.mirButton];
       
        [self addButtons];
        
        if(self.devices.dual_camera == 3){
            for (int i = 0;  i < 3; i++) {

                    NSArray *imageArray2 = @[@"vl0_change_camera",@"vl0_change_camera",@"vl0_change_camera"];
                    NSArray *imageArray3 = @[@"vl0_change_camera",@"vl0_change_camera",@"vl0_change_camera"];
                    NSArray *titleArray = @[@"门外上",@"门内",@"门外下"];
                    NSArray *titleArray2 = @[@"门外上",@"门内",@"门外下"];
                   
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                   [button setImage:[UIImage imageNamed:imageArray2[i]] forState:UIControlStateNormal];
                   [button setImage:[UIImage imageNamed:imageArray3[i]] forState:UIControlStateSelected];
                    
                   [button setTitle:titleArray[i] forState:UIControlStateNormal];
                   [button setTitle:titleArray2[i] forState:UIControlStateSelected];
                    button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13];
                   [self.view addSubview:button];
                   [button mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.centerY.equalTo(self.view.mas_centerY).offset((i-1) * 80);
                        make.width.mas_equalTo(80);
                        make.height.mas_equalTo(80);
                        make.right.equalTo(self.view.mas_right);
                    }];
                    button.tag = 4000 + i;
                   [button addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
                   [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                   [button SG_imagePositionStyle:SGImagePositionStyleTop spacing:5];
                   [self.view bringSubviewToFront:button];

             }
        }
        
    });
    
}

#pragma mark 计时
- (void)showTime
{
    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    NSDate *today = [NSDate date];//得到当前时间
    unsigned int unitFlags2 = NSCalendarUnitSecond;
    NSDateComponents *s = [cal components:unitFlags2 fromDate:self.date toDate:today options:0];
 
    NSLog(@"showTime time === %ld",(long)s.second);
    
    if(s.second >= 105 ){
        
        if(s.second == VL5Closetime){
            NSLog(@"showTime time out");
            [self byebyeCall];
        }else{
             self.vl0TimeLabel.text = [NSString stringWithFormat:@"通话将在 %ld 秒后自动挂断",VL5Closetime - s.second];
        }
    }else{
        
        //用来得到具体的时差
        unsigned int unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        NSDateComponents *d = [cal components:unitFlags fromDate:self.date toDate:today options:0];
        self.vl0TimeLabel.text = [NSString stringWithFormat:@"直播：%02ld:%02ld:%02ld",(long)[d hour], (long)[d minute], (long)[d second]];
        
    }
    [self.view bringSubviewToFront:self.vl0TimeLabel];
    
}

#pragma mark timeout
- (void)RecvCallTimeoutMsg:(NSNotification*)notification
{
    NSLog(@"对端设备断开，数据超时挂断");
    [self byebyeCall];
}

#pragma mark: 开锁处理结果
- (void)open_smart_lock_response:(NSNotification*)notification
{
    [SVProgressHUD showWithStatus:@"正在开锁中..."];
}

#pragma mark 开锁结果
- (void)open_smart_lock_result:(NSNotification*)notification
{
    
        NSDictionary *dict = (NSDictionary*)notification.object;
         __weak VL5CallVideoVController *weakSelf = self;
          if(_open_vl0_time){
             dispatch_source_cancel(_open_vl0_time);
              _open_vl0_time = nil;
          }
         
         if(_can_open_vl0_time){
             dispatch_async(dispatch_get_main_queue(), ^{
                  UIButton *sender = [self.view viewWithTag:1314];
                 [sender removeFromSuperview];
                  sender = nil;
                 
                   if (weakSelf.lockImageview) {
                      [weakSelf.lockImageview removeFromSuperview];
                       weakSelf.lockImageview = nil;
                  }
                 
                 if (self.devices.flexible_unlock != 1) {
                    UIButton *sender1 = [self.view viewWithTag:2002];
                   [sender1 setImage:[UIImage imageNamed:@"remote_vl0_lock_2"] forState:UIControlStateNormal];
                    sender1.userInteractionEnabled = NO;
                 }
             });
             
            dispatch_source_cancel(_can_open_vl0_time);
             _can_open_vl0_time = nil;
         }

        switch ([[dict objectForKey:@"ret"] intValue]) {
            case 0:
            {
                UIButton *sender = [self.view viewWithTag:1000];
                sender.enabled = NO;
               [sender setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                [SVProgressHUD dismiss];
                [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Unlocking successful", nil)];
            }
                break;
                
            case 1:
            {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"开锁失败", nil)];
            
            }
                break;
                
            case 2:
            {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"门已反锁", nil)];
                
            }
                break;
                
            case 3:
            {
               
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"密码已冻结", nil)];
                
            }
                break;
                
            default:
            {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"开锁失败", nil)];
            }
                break;
        }
         
         return;
   
}


#pragma mark 设备状态变更
/*呼叫VL1系列时，在发送唤醒指令过程中，监听设备上线结果，当设备从睡眠变更为上线时，修改标记位，发送呼叫指令
 需要特别处理的是：
 发送唤醒指令时，设备从之前的睡眠（stat = 2 ）状态，变更为在线(stat = 1)状态时，设备会先断开之前的通道复用，服务器会先返回 设备掉线结果，在5秒之内会立即上线，所以客户端在处理时，在视频呼叫界面，针对设备掉线时服务器发出的掉线结果，会延迟5秒调用 如果5秒内设备上线 此时呼叫界面不挂断，5秒后设备还是离线 说明设备确实是离线！
 */
- (void)devst:(NSNotification*)notification
{
    /*
     {
         bid = 1fd834a600472ebe24cb01e03f9416d1;
         method = devst;
         name = "e0d31a150c6f-1fd834a6";
         remoteupg = 2;
         role = 27;
         status = 0;
         stat = 0;
         type = 27;
         uid = 1fd834a600472ebe24cb01e03f9416d1;
     }
    */
    
    NSDictionary *dict = (NSDictionary*)notification.object;
    
    NSString *bid = [dict objectForKey:@"bid"];
    if (![bid isEqualToString:self.bid]) {
        return;
    }
    
    NSLog(@"devst --- notification --- %@ \n ",notification.object);

    __weak VL5CallVideoVController *weakSelf = self;
    if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 1) {
        self.cancelpost = YES;
    }
    
      if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 1) {
          
          self.cancelpost = YES;
          if (!self.isSendInvite) {
              [self makeCall];
               self.isSendInvite = YES;
          }
      // 设备不在线的情况下 拨打了视频
      }else if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 2){
      
              if(_wake_up_timer){
                dispatch_source_cancel(_wake_up_timer);
                  _wake_up_timer  = nil;
              }
              // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
              __block int timeout = 30; // 倒计时时间
              self.cancelpost = NO;
              dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
             _wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
              dispatch_source_set_timer(_wake_up_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
              dispatch_source_set_event_handler(_wake_up_timer, ^{
                  if(self.cancelpost){ // 倒计时结束，关闭
                      dispatch_source_cancel(weakSelf.wake_up_timer);
                      dispatch_async(dispatch_get_main_queue(), ^{
                          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                              if (!self.isSendInvite) {
                                  [self makeCall];
                                   self.isSendInvite = YES;
                              }
                          });
                      });
                  }else{
                       NSString *Str = [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                      [YKBusinessFramework equesSendData:Str];
                       timeout--;
                      if (timeout <= 0) {
                          dispatch_source_cancel(weakSelf.wake_up_timer);
                          weakSelf.wake_up_timer = nil;
                          dispatch_async(dispatch_get_main_queue(), ^{
                              [SVProgressHUD showErrorWithStatus:@"设备处于睡眠中，还未唤醒！"];
                          });
                      }
                  }
              });
              dispatch_resume(_wake_up_timer);
          
      }else if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 0){
          self.cancelpost = NO;
          
          if(self.sucess_call){
              [SVProgressHUD showErrorWithStatus:@"设备掉线！" duration:1.5];
              [self byebyeCall];
          }
      }

}

#pragma mark 设备呼叫时报错 可以重试
- (void)errorVideo:(NSNotification*)notification
{
    
    NSString *notication = notification.name;
    
    //rtc服务器掉线 重新初始化
    if ([notication isEqualToString:equesOnMessageVideocConnectPeerFail]) {
        
        [self makeCall];
    
    }else{
        [SVProgressHUD showErrorWithStatus:@"创建数据通道失败,APP退出重新登录再呼叫" duration:3];
    }

}

#pragma mark 拨打视频
- (void) makeCall{
    
        NSLog(@"进入makecall method");
        
        if (self.netType == 1) {
            
            NSString *ipport = [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpport"];
            NSString *ip =     [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpip"];
            
            self.rtcip = ip;
            self.rtcport = [ipport intValue];
            self.netType = self.devices.netType;
        }else{
            
            if (self.devices.netType == 1) {
                
                NSString *ipport = [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpport"];
                NSString *ip =     [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpip"];
                
                self.rtcip = ip;
                self.rtcport = [ipport intValue];
            }else{
                
                NSString *ipport = [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcserverport"];
                NSString *ip =     [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcserverip"];
                self.rtcip = ip;
                self.rtcport = [ipport intValue];
                
                
            }
            self.netType = self.devices.netType;
            
        }
    
    
        [YKBusinessFramework rtc_initWithUserId:[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"] andIP:self.rtcip andPort:self.rtcport net_type:self.netType];
            
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
           [YKBusinessFramework rtc_make_Call:self.bid showView:self.call_view peer_id:self.peer_id camera_width:self.devices.videocall_width camera_height:self.devices.videocall_height isInvite:self.is_invite userID:[Tooles get_uid]  type:EQUESVL5 path:@"" isH264:NO camera_id:self.devices.camera_id denoise:0 op_type:0 dataBlock:^(char *picdata, int data_size, int yuv_wdith, int yuv_height, const uint8_t *src_y, int src_stride_y, const uint8_t *src_u, int src_stride_u, const uint8_t *src_v, int src_stride_v) {
        
        }];
    
        
    });

}


#pragma mark 添加视频控件
- (void)addCallview
{
     self.call_view = [[UIView alloc]initWithFrame:CGRectMake(0,(kScreenHeight-kScreenWidth*self.w_h)/2,kScreenWidth,kScreenWidth*self.w_h)];
    [self.view addSubview:self.call_view];
}

#pragma mark 添加计时控件
- (UILabel*)vl0TimeLabel
{
    if (!_vl0TimeLabel) {
         _vl0TimeLabel = [[UILabel alloc]init];
         _vl0TimeLabel.textAlignment = NSTextAlignmentLeft;
         _vl0TimeLabel.textColor = [UIColor whiteColor];
         _vl0TimeLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        [self.view addSubview:_vl0TimeLabel];
        [_vl0TimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(14);
            make.top.equalTo(_call_view.mas_top).offset(10);
            make.width.mas_equalTo(240);
            make.height.mas_equalTo(30);
        }];
    }
    return _vl0TimeLabel;
}

#pragma mark 挂断
- (void) byebyeCall{
    
    NSLog(@"bye bye call.");
    
    if(_wake_up_timer){
       dispatch_source_cancel(_wake_up_timer);
        _wake_up_timer = nil;
    }
    if(_timer){
      [_timer invalidate];
       _timer = nil;
    }
 
    
    if(_waittingVideoTimer){
      [_waittingVideoTimer invalidate];
       _waittingVideoTimer = nil;
    }


    [SVProgressHUD showWithStatus:@"正在挂断..."];
    [YKBusinessFramework rtc_hangup:self.bid];
    [YKBusinessFramework rtc_changSound:0];
    [YKBusinessFramework rtc_uninit];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD showSuccessWithStatus:@"已挂断"];
        
        if (self.OnePresent) {
            [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }
        
        
    });
    
    NSDate* dat = [NSDate date];
    NSTimeInterval hangupTime = [dat timeIntervalSince1970];
    AppDelegate *de = (AppDelegate*) [[UIApplication sharedApplication] delegate];
    de.hangupTime = hangupTime;
   
}


#pragma mark 对讲按钮展示
- (UIButton*)speakButton
{
    if (!_speakButton) {
         _speakButton = [[UIButton alloc]init];
         _speakButton.backgroundColor = [UIColor clearColor];
         _speakButton.layer.cornerRadius = 17;
         _speakButton.layer.masksToBounds = YES;
        [_speakButton setImage:[UIImage imageNamed:@"voice_no_touch_vl2"] forState:UIControlStateNormal];
        [_speakButton setImage:[UIImage imageNamed:@"voice_touch_vl2"] forState:UIControlStateSelected];
        [_speakButton addTarget:self action:@selector(doublespeakButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_speakButton];
        [_speakButton mas_remakeConstraints:^(MASConstraintMaker *make){
            make.height.mas_equalTo(44);
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(-30);
            make.centerX.mas_equalTo(self.view);
            make.width.mas_equalTo(100);
        }];
    }
    return _speakButton;
}
    
- (void)doublespeakButtonEvent:(UIButton*)sender
{
    NSLog(@"holdSpeakButton.selected = %u",sender.selected);
    
    sender.selected = !sender.selected;
    
    if (sender.selected == YES) {
    
        [YKBusinessFramework rtc_changSound:_soundType];
        [YKBusinessFramework rtc_AudioPlayEnable:true];
        [YKBusinessFramework rtc_AudioPlayRecordEnable:true];
        
        [_mirButton setImage:[UIImage imageNamed:@"mute_off_vl2"] forState:UIControlStateNormal];
         _bopenMicro = YES;
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Intercom Open", nil) duration:1.2];
        
    }else{
       
        if (_bopenMicro) {
            [_mirButton setImage:[UIImage imageNamed:@"mute_off_vl2"] forState:UIControlStateNormal];
        }else{
            [_mirButton setImage:[UIImage imageNamed:@"mute_on_vl2"] forState:UIControlStateNormal];
        }
        [YKBusinessFramework rtc_AudioPlayEnable:_bopenMicro];
        [YKBusinessFramework rtc_AudioPlayRecordEnable:false];
    
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Intercom Close", nil) duration:1.2];
    }
    
}
#pragma mark 静音按钮展示
- (UIButton*)mirButton
{
    if (!_mirButton) {
         _mirButton = [[UIButton alloc] init];
        [_mirButton setImage:[UIImage imageNamed:@"mute_on_vl2.png"] forState:UIControlStateNormal];
         _mirButton.enabled = YES;
        [_mirButton addTarget:self action:@selector(mircoclickBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_mirButton];
        [_mirButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.speakButton.mas_left).mas_offset(-48);
            make.width.height.mas_equalTo(NewButtonSize);
            make.centerY.equalTo(self.speakButton.mas_centerY);
        }];
    }
    return _mirButton;
}

- (void)mircoclickBtn:(UIButton*)sender
{
    _bopenMicro = !_bopenMicro;
    NSLog(@"current bopenMicro = %d.",_bopenMicro);
    if (_bopenMicro) {
     
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Mute mode is turned on", nil) duration:1.2];
        [_mirButton setImage:[UIImage imageNamed:@"mute_on_vl2.png"] forState:UIControlStateNormal];
    }else{

        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Mute mode is turned off", nil) duration:1.2];
        [_mirButton setImage:[UIImage imageNamed:@"mute_off_vl2.png"] forState:UIControlStateNormal];
    }
    [YKBusinessFramework rtc_AudioPlayEnable:_bopenMicro];
}

#pragma mark 挂断按钮展示
- (UIButton*)hanupButton
{
    if (!_hanupButton) {
        
        _hanupButton = [[UIButton alloc] init];
        [_hanupButton setImage:[UIImage imageNamed:@"vl0_hang_up.png"] forState:UIControlStateNormal];
        [_hanupButton setImage:[UIImage imageNamed:@"vl0_hang_up.png"] forState:UIControlStateSelected];
        [_hanupButton addTarget:self action:@selector(hanupButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_hanupButton];
        [_hanupButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.speakButton.mas_right).mas_offset(48);
            make.width.height.mas_equalTo(NewButtonSize);
            make.centerY.equalTo(self.speakButton.mas_centerY);
        }];
        
    }
    
    return _hanupButton;
}

- (void)hanupButtonClick:(UIButton*)sender
{

    [self byebyeCall];
    
}


#pragma mark 抓拍 原声 开锁 切换摄像头等按钮
- (void)addButtons{
    //创建三个按钮抓拍 变声 开锁
    NSArray *imageArray2 = @[@"vl2_capture_photo",@"voice_real_vl2",@"remote_vl0_lock_1",@"vl0_change_camera"];
    NSArray *imageArray3 = @[@"vl2_capture_photo",@"voice_man_vl2",@"remote_vl0_lock_1",@"vl0_change_camera_gray"];
    
    NSArray *titleArray = @[@"抓拍",@"原声",@"开锁",@"切换摄像头"];
    NSArray *titleArray2 = @[@"抓拍",@"大叔",@"开锁",@"切换摄像头"];
    
    CGFloat width;
    width = [UIScreen mainScreen].bounds.size.width / 3;
    int height = 60;
    int count = 0;
    count = self.IsShowOpenLock ? 3 : 2;
    
    if(self.devices.dual_camera == 1 || self.devices.dual_camera  == 2 || self.devices.dual_camera  == 4){
        count ++;
        width = [UIScreen mainScreen].bounds.size.width / count;
       
    }
    
    for (int i = 0;  i < count; i++) {

        if (self.IsShowOpenLock) {
          
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
               [button setImage:[UIImage imageNamed:imageArray2[i]] forState:UIControlStateNormal];
               [button setImage:[UIImage imageNamed:imageArray3[i]] forState:UIControlStateSelected];
            
               [button setTitle:titleArray[i] forState:UIControlStateNormal];
               [button setTitle:titleArray2[i] forState:UIControlStateSelected];
                button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13];
               [self.view addSubview:button];
               [button mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.view.mas_bottom).offset(-180);
                    make.width.mas_equalTo(width);
                    make.height.mas_equalTo(height);
                    make.left.mas_equalTo(self.view.mas_left).offset(width*i);
                }];
            
                button.tag = 2000 + i;
            
               [button addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
               [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
               [self.view bringSubviewToFront:button];
            
               [button SG_imagePositionStyle:SGImagePositionStyleTop spacing:5];
            
            if (i == 2) {
                
                if(self.devices.flexible_unlock != 1){
                    self.lockImageview = [[UIImageView alloc]init];
                   [self.view addSubview:self.lockImageview];
                   [self.lockImageview mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(button.mas_bottom).offset(10);
                        make.width.mas_equalTo(16);
                        make.height.mas_equalTo(17);
                        make.centerX.mas_equalTo(button.mas_centerX).offset(-20);
                    }];
                    
                    
                    if (self.devices.flexible_unlock != 1){
                        self.lockImageview.animationImages =  [NSArray arrayWithObjects:
                                                             [UIImage imageNamed:@"vl0_count1@3x.png"],
                                                             [UIImage imageNamed:@"vl0_count2@3x.png"],
                                                             [UIImage imageNamed:@"vl0_count3@3x.png"],
                                                             [UIImage imageNamed:@"vl0_count4@3x.png"],[UIImage imageNamed:@"vl0_count5@3x.png"],nil];
                        self.lockImageview.animationDuration = 0.5;
                        self.lockImageview.animationRepeatCount = 0;
                        self.lockImageview.tag = 1315;
                       [self.lockImageview startAnimating];
                       [self.view bringSubviewToFront:self.lockImageview];
                   }
                    
                   UIButton *lock_button = [UIButton buttonWithType:UIButtonTypeCustom];
                  [self.view addSubview:lock_button];
                  [lock_button mas_makeConstraints:^(MASConstraintMaker *make) {
                       make.left.equalTo(self.lockImageview.mas_right);
                       make.width.mas_equalTo(40);
                       make.height.mas_equalTo(20);
                       make.centerY.mas_equalTo(self.lockImageview.mas_centerY);
                   }];
                   lock_button.tag = 1314;
                  [lock_button setTitleColor:[HexChangeRGB colorWithHexString:@"#FFECC0"] forState:UIControlStateNormal];
                   lock_button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
                  [self.view bringSubviewToFront:lock_button];
                   
                    if (self.devices.flexible_unlock != 1) {
                        __block int timeout = self.canOpenLockTime; // 倒计时时间
                       dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                       self.can_open_vl0_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                       dispatch_source_set_timer(self.can_open_vl0_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                       dispatch_source_set_event_handler(self.can_open_vl0_time, ^{
                            timeout--;
                           
                            dispatch_async(dispatch_get_main_queue(), ^{
                                 UIButton *sender = [self.view viewWithTag:1314];
                                [sender setTitle:[NSString stringWithFormat:@"00:%02d",timeout] forState:UIControlStateNormal];
                                [sender SG_imagePositionStyle:SGImagePositionStyleDefault spacing:4];
                            });
                           if (timeout <= 0) {
                               if(self.can_open_vl0_time){
                                  
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       
                                        UIButton *sender = [self.view viewWithTag:1314];
                                       [sender removeFromSuperview];
                                        sender = nil;
                                       
                                      
                                       if (self.lockImageview) {
                                         [self.lockImageview removeFromSuperview];
                                          self.lockImageview = nil;
                                        }
                                       
                                       [self dissMiss];
                                       
                                        UIButton *sender1 = [self.view viewWithTag:2002];
                                       [sender1 setImage:[UIImage imageNamed:@"remote_vl0_lock_2"] forState:UIControlStateNormal];
                                        sender1.userInteractionEnabled = NO;
                                   });
                                   
                                  dispatch_source_cancel(self.can_open_vl0_time);
                                   self.can_open_vl0_time = nil;
                               }
                           }
                       });
                       dispatch_resume(self.can_open_vl0_time);
                        
                    }
                }
                
           }

        }else{
            
            NSArray *imageArray2 = @[@"vl2_capture_photo",@"voice_real_vl2",@"vl0_change_camera"];
            NSArray *imageArray3 = @[@"vl2_capture_photo",@"voice_man_vl2",@"vl0_change_camera_gray"];
            NSArray *titleArray = @[@"抓拍",@"原声",@"切换摄像头"];
            NSArray *titleArray2 = @[@"抓拍",@"大叔",@"切换摄像头"];
           
            if(self.devices.dual_camera < 1 || self.devices.dual_camera == 3){

                width = [UIScreen mainScreen].bounds.size.width / 2;
               
            }
            
            if(self.devices.dual_camera == 1 || self.devices.dual_camera  == 2 || self.devices.dual_camera  == 4){
                width = [UIScreen mainScreen].bounds.size.width / count;
            }
            
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
           [button setImage:[UIImage imageNamed:imageArray2[i]] forState:UIControlStateNormal];
           [button setImage:[UIImage imageNamed:imageArray3[i]] forState:UIControlStateSelected];
            
           [button setTitle:titleArray[i] forState:UIControlStateNormal];
           [button setTitle:titleArray2[i] forState:UIControlStateSelected];
            button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13];
           [self.view addSubview:button];
           [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.view.mas_bottom).offset(-180);
                make.width.mas_equalTo(width);
                make.height.mas_equalTo(height);
                make.left.mas_equalTo(self.view.mas_left).offset(width*i);
            }];
            button.tag = 3000 + i;
           [button addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
           [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
           [button SG_imagePositionStyle:SGImagePositionStyleTop spacing:5];
           [self.view bringSubviewToFront:button];
            
         }
     }
}


- (void)BtnClick:(UIButton*)sender
{
    switch (sender.tag) {
        
        case 3000:
        case 2000:
        {
            [self save_cap];
        }
            break;
            
        case 3001:
        case 2001:
        {
            sender.selected =  !sender.selected;
             self.soundType = sender.selected;
            [YKBusinessFramework rtc_changSound:self.soundType];
        }
            break;
            
        case 2002:
        {
            
            //是否要验证密码
            if (self.devices.sercurityStatus) {
               
                [self showPsdView];
                
            }else{
                [self postLock];
            }
            
        }
            break;
        case 3002:
        case 2003:
        {
            
            __block int timeout = 6; // 倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            self.change_camera_post = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
            dispatch_source_set_timer(self.change_camera_post,dispatch_walltime(NULL, 0),1*NSEC_PER_SEC, 0); //每500毫秒执行
            dispatch_source_set_event_handler(self.change_camera_post, ^{
            
                     timeout --;
                    if (timeout <= 0) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if([SVProgressHUD isVisible]){
                               [SVProgressHUD dismiss];
                            }
                        });
                        dispatch_source_cancel(self.change_camera_post);
                        self.change_camera_post = nil;
                    }
            });
            dispatch_resume(self.change_camera_post);
            
        
            if(self.devices.dual_camera == 4){
                
                self.camera_index = !self.camera_index;
                int index = self.camera_index ? 2 : 0;
                // 其中0表示门外上摄像头，1表示门内摄像头；2表示门外下摄像头
                [SVProgressHUD showWithStatus:@"切换中..."];
             
                [YKBusinessFramework switch_camera:index bid:self.bid];
                
                
            }else{
                // 其中0表示门外上摄像头，1表示门内摄像头；2表示门外下摄像头
                self.camera_index = !self.camera_index;
                [SVProgressHUD showWithStatus:@"切换中..."];
              
                [YKBusinessFramework switch_camera:self.camera_index bid:self.bid];
               
            }
            
        }
            break;
            
        case 4000:
        case 4001:
        case 4002:
        {
            __block int timeout = 6; // 倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            self.change_camera_post = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
            dispatch_source_set_timer(self.change_camera_post,dispatch_walltime(NULL, 0),1*NSEC_PER_SEC, 0);
            dispatch_source_set_event_handler(self.change_camera_post, ^{
            
                     timeout --;
                    if (timeout <= 0) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if([SVProgressHUD isVisible]){
                               [SVProgressHUD dismiss];
                            }
                        });
                        dispatch_source_cancel(self.change_camera_post);
                        self.change_camera_post = nil;
                    }
            });
            dispatch_resume(self.change_camera_post);
            
            
            [SVProgressHUD showWithStatus:@"切换中..."];
            [YKBusinessFramework switch_camera:sender.tag-4000 bid:self.devices.bid];
            
        }
            break;
            
            
        default:
            break;
    }
}


#pragma mark 切换摄像头
- (void)switch_camera_response:(NSNotification*)notification
{
    
    if(self.change_camera_post){
        dispatch_source_cancel(self.change_camera_post);
        self.change_camera_post = nil;
    }
    NSDictionary *dict = (NSDictionary*)notification.object;
    
    if ([dict.allKeys containsObject:@"camera_id"]){
         int cameraid = [[dict objectForKey:@"camera_id"] intValue];
        if (_camera_id != cameraid) {
            _camera_id = cameraid;
            [YKBusinessFramework change_video_angle:_camera_id];
        }
    }
    
    if (self.devices.dual_camera == 5) {
        if ([dict.allKeys containsObject:@"index"]){
            self.camera_index = [[dict objectForKey:@"index"] intValue];
        }
    }
    
    [SVProgressHUD dismiss];
    [SVProgressHUD showSuccessWithStatus:@"切换成功" duration:1.5];
}


// 展示安全密码设置界面
- (void)showPsdView
{
     self.lowView = [[SecurityPwdView alloc]initWithSetSercurityPsd:@"输入安全密码" andSubTitle:@"输入安全密码，用于App远程开锁" iconName:@"" type:2 deviceBid:self.devices.bid isView:NO];
     self.lowView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:self.lowView];
    [self.lowView show];
}

- (void)dissMiss
{
    if (self.lowView) {
        [self.lowView removeFromSuperview];
         self.lowView = nil;
    }
}


- (void)sercurityCode:(NSString *)code type:(int)type
{
    NSLog(@"code-->%@",code);
    //去验证 验证完 发送开锁指令
    if ([self.devices.sercurityCode isEqualToString:code]) {
        [self postLock];
        [self dissMiss];
    }else{
        [SVProgressHUD showErrorWithStatus:@"安全密码有误，请重新输入！"];
    }
}

- (void)postLock
{
   
     [SVProgressHUD showWithStatus:@"发送开锁指令中..."];
     
    NSString *user_id = [[NSUserDefaults standardUserDefaults] objectForKey:@"usr_bid"];
    
     __weak VL5CallVideoVController *weakSelf = self;
    [YKBusinessFramework open_lockDeviceBid:self.devices.bid Userbid:user_id];
    
     // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
     __block int timeout = 15; // 倒计时时间
     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     _open_vl0_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
     dispatch_source_set_timer(_open_vl0_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
     dispatch_source_set_event_handler(_open_vl0_time, ^{
         timeout--;
         if (timeout <= 0) {
             if(weakSelf.open_vl0_time){
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if ([SVProgressHUD isVisible]) {
                         [SVProgressHUD dismiss];
                         [SVProgressHUD showErrorWithStatus:@"开锁超时"];
                     }
                 });
                
                dispatch_source_cancel(weakSelf.open_vl0_time);
                 weakSelf.open_vl0_time = nil;

             }
         }
     });
     dispatch_resume(_open_vl0_time);
}


- (void)save_cap
{
    [SVProgressHUD show];

    UIImage *image = [self screenshotOfView:self.call_view];
    
    [SVProgressHUD dismiss];
    
    [self saveImageToPhotos:image];
}


#pragma mark 抓拍处理
// 截取 UIView 的方法
- (UIImage *)screenshotOfView:(UIView *)view {
    
    // 获取主屏幕对象
    UIScreen *mainScreen = [UIScreen mainScreen];
    // 获取当前屏幕的缩放因子（scale）
    CGFloat screenScale = mainScreen.scale;

    NSLog(@"当前屏幕的缩放因子为：%.2f", screenScale);

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, screenScale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



#pragma mark VL0抓拍保存到本地
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 11.0) {
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            
            dispatch_async(dispatch_get_main_queue() , ^{
                if (status == PHAuthorizationStatusNotDetermined  || status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
                    UIAlertView *albumaccessAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Album permissions didn't open, please in general privacy ding-dong album open photo album service", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"sure", nil), nil];
                    albumaccessAlertView.tag = 704;
                    [albumaccessAlertView show];
                    return;
                }
            });
        }];
    }else{
        
        [self checkAlbumAccess];
        
    }
    
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}


- (void)checkAlbumAccess{
    
    if (![Tooles albumAccess]) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            [Tooles iOSv8AlertControllershow:NSLocalizedString(@"Album permissions didn't open, please in general privacy ding-dong album open photo album service", nil) actionTile1:NSLocalizedString(@"cancel", nil) actionTitle2:NSLocalizedString(@"sure", nil) currentController:self actionBlock:(__bridge void *)(^(UIAlertAction *actroin){
                
                if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
                    
                AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                if (authStatus == AVAuthorizationStatusRestricted || // 此应用程序没有被授权访问的照片数据
                    authStatus == AVAuthorizationStatusDenied)   // 用户已经明确否认了这一照片数据的应用程序访问
                {
                    //无权限 引导去开启
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication]canOpenURL:url]) {
                       [[UIApplication sharedApplication]openURL:url];
                    }
                }
            }
                  NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            })];
        
        }else{
            UIAlertView *albumaccessAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Album permissions didn't open, please in general privacy ding-dong album open photo album service", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"sure", nil), nil];
             albumaccessAlertView.tag = 704;
            [albumaccessAlertView show];
        }
        return;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 704)//相册访问权限
    {
        if (buttonIndex == 1)
        {
            void (^mysetting)() = ^(){

                 NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            };
            mysetting();
        }
    }
}

// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    if(!error)
    {
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Save to phone album", nil)];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"save failure", nil)];
    }

}

- (UIImage*)createCaptureView:(UIImage*)image
{
    UIImage *saveImage = image;
    UIView *view1 = [[UIView alloc]init];
    view1.frame = CGRectMake(0,0,saveImage.size.height,saveImage.size.width);
    UIImageView *imageview = [[UIImageView alloc]init];
    [view1 addSubview:imageview];
    [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(saveImage.size.height);
        make.width.mas_equalTo(saveImage.size.width);
        make.centerX.equalTo(view1.mas_centerX);
        make.centerY.equalTo(view1.mas_centerY);;
    }];
    imageview.image = saveImage;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    if (self.devices.camera_id > 0 && self.devices.camera_id != 4) {
        if (self.devices.camera_id == 3) {
            transform = CGAffineTransformRotate(transform,M_PI_2);
        }else if (self.devices.camera_id == 5) {
            
        }else{
            transform = CGAffineTransformRotate(transform, -M_PI_2);
        }
    }else{
        if ( self.devices.camera_id == 4) {
            transform = CGAffineTransformRotate(transform, M_PI);
        }else{
            transform = CGAffineTransformRotate(transform, M_PI_2);
        }
    }
    
     imageview.transform = transform;
    [self.view insertSubview:view1 atIndex:0];
    
    UIImage *imsge = [self captureView:view1];
    
    view1.hidden = YES;
    return imsge;
    
}

#pragma mark: view获得截图 生成图片
-(UIImage*)captureView:(UIView *)theView{
    CGRect rect = theView.frame;
    if ([theView isKindOfClass:[UIScrollView class]]) {
        rect.size = ((UIScrollView *)theView).contentSize;
    }
    UIGraphicsBeginImageContext(rect.size);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

#pragma mark 视频呼叫加载动画
- (void)addVoiceImage{
     _annimationImage = [[UIImageView alloc]init];
    [self.view addSubview:_annimationImage];
    [_annimationImage mas_makeConstraints:^(MASConstraintMaker *make){
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY).offset(-100);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(100);
    }];
    [self.view bringSubviewToFront:_annimationImage];
    
}

- (void)loadingForVideoAnimation{

    _annimationImage.animationImages = [NSArray arrayWithObjects:
                                   [UIImage imageNamed:@"annimation_new_loading_1"],
                                   [UIImage imageNamed:@"annimation_new_loading_2"],
                                   [UIImage imageNamed:@"annimation_new_loading_3"],
                                   [UIImage imageNamed:@"annimation_new_loading_4"],
                                   [UIImage imageNamed:@"annimation_new_loading_5"],
                                   [UIImage imageNamed:@"annimation_new_loading_6"],
                                   [UIImage imageNamed:@"annimation_new_loading_7"],
                                   [UIImage imageNamed:@"annimation_new_loading_8"],
                                   nil];

     _annimationImage.animationDuration = 1.2;
     _annimationImage.animationRepeatCount = 25;
    [_annimationImage startAnimating];
     self.waittingVideoTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(loadingForVideoTimeOut:) userInfo:nil repeats:NO];
    [self.view bringSubviewToFront:_annimationImage];
}

// 拨打视频超时后，显示提醒文字
- (void)loadingForVideoTimeOut:(NSTimer *)timer{

    [_annimationImage stopAnimating];
    [_annimationImage stopAnimating];
     _annimationImage.hidden = YES;
    NSLog(@"视频超时");
    [SVProgressHUD showErrorWithStatus:@"呼叫超时！" duration:2.0];
}

#pragma mark 挂断按钮展示
- (UIButton*)hanup_Button
{
    if (!_hanup_Button) {
        
        _hanup_Button = [[UIButton alloc] init];
       [_hanup_Button setImage:[UIImage imageNamed:@"vl0_hang_up.png"] forState:UIControlStateNormal];
       [_hanup_Button setImage:[UIImage imageNamed:@"vl0_hang_up.png"] forState:UIControlStateSelected];
        [_hanup_Button addTarget:self action:@selector(hanupButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_hanup_Button];
        [_hanup_Button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.width.height.mas_equalTo(80);
            make.bottom.equalTo(self.view.mas_bottom).offset(-80);
        }];
        [_hanup_Button bringSubviewToFront:_hanup_Button];
    }
    
    return _hanup_Button;
}

#pragma mark 添加计时控件
- (UILabel*)loadingLabel
{
    if (!_loadingLabel) {
         _loadingLabel = [[UILabel alloc]init];
         _loadingLabel.textAlignment = NSTextAlignmentCenter;
         _loadingLabel.textColor = [UIColor whiteColor];
         _loadingLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
        [self.view addSubview:_loadingLabel];
        [_loadingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.top.equalTo(self.annimationImage.mas_bottom).offset(10);
            make.width.mas_equalTo(240);
            make.height.mas_equalTo(30);
        }];
    }
    return _loadingLabel;
}


@end
